package com.jinyi.wwdeng.ui.main.act

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.jinyi.base.utils.ActivityStackManager
import com.jinyi.base.utils.BarUtils
import com.jinyi.base.utils.log.HHLog
import com.jinyi.lib_baseadapter.BGAOnItemChildClickListener
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.analysis.TestAnalysisAddEvent
import com.jinyi.wwdeng.databinding.ActCreditApplyBinding
import com.jinyi.wwdeng.pro.ProMvpAct
import com.jinyi.wwdeng.ui.main.adapter.CreditApplyLableAdapter
import com.jinyi.wwdeng.ui.main.contract.CreditApplyContract
import com.jinyi.wwdeng.ui.main.impl.CreditApplyPresenterImpl
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import org.json.JSONObject
import java.math.BigDecimal

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/24 10:39
 * @Annotation：贷款申请
 */
class CreditApplyAct: ProMvpAct<CreditApplyContract.View,CreditApplyPresenterImpl>(),CreditApplyContract.View {

    lateinit var binding: ActCreditApplyBinding
    //广播接收器
    private var mRecevier: ProcessUpdatedRecevier? = null
    private var mItemAdapter: CreditApplyLableAdapter? = null
    //是否点击申请贷款，只有主动点击申请按钮才会处理总流程刷新通知
    private var isApplyClick = false

    override fun getRootView(): View {
        binding = ActCreditApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): CreditApplyPresenterImpl {
        return CreditApplyPresenterImpl()
    }

    override fun initView() {
        initPresenter()
        binding.titleLayout.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        initRefreshLayout()
        initRecyclerView()
        registerUpdateRecevier()
    }

    override fun initListener() {
        //返回
        binding.ivBack.setOnClickListener {
            finish()
        }
        //客服
        binding.ivKefu.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"CreditApply Page")
        }
        //确定
        binding.btnConfirm.setOnClickListener {
            isApplyClick = true
            /**
             * 流程
             * 1、需要先通过流程接口，判断订单状态和申请状态
             * 2、创建贷款申请订单
             * 3、创建贷款申请订单成功后再验证总流程，返回首页显示审核状态
             */
            showLoading("")
            //发送更新总流程通知
            val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATE)
            sendBroadcast(intent)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_APPLY_CONFIRM,"")
        }
    }

    override fun initData() {
        showLoading("")
        presenter.loadCreditApplyRequest()
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            presenter.loadCreditApplyRequest()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 初始化列表
     */
    private fun initRecyclerView() {
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        mItemAdapter = CreditApplyLableAdapter(binding.recyclerView)
        binding.recyclerView.adapter = mItemAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        mItemAdapter!!.setOnItemChildClickListener(BGAOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        })
    }

    /**
     * 设置贷款额度预览信息
     */
    override fun showCreditApplyInfoData(data: JSONObject) {
        binding.tvAmountUnit.text = data.optString("currency")
        binding.tvAmount.text = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()

        binding.tvDays.text = data.optString("days")

        val array = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        for (i in 0..<array.length()){
            dataList.add(array.optJSONObject(i))
        }
        mItemAdapter!!.data = dataList
    }

    /**
     * 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showCreditApplyFailed() {
        ActivityStackManager.finishAllActivity(MainAct::class.java)
    }

    /**
     * 贷款申请订单创建成功
     */
    override fun showCreditApplyOrderCreateSuccess(data: JSONObject) {
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        //注销广播接收器
        if (mRecevier != null){
            unregisterReceiver(mRecevier)
            mRecevier = null
        }
        //发送更新总流程通知
        val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATE)
        sendBroadcast(intent)
        //返回首页
        ActivityStackManager.finishAllActivity(MainAct::class.java)
    }

    override fun onRequestFinish() {
        super.onRequestFinish()
        hideLoading()
        binding.refreshLayout.finishRefresh()
    }

    /**
     * 注册更新用户流程状态广播
     */
    private fun registerUpdateRecevier() {
        mRecevier = ProcessUpdatedRecevier(this)
        val intentFilter = IntentFilter()
        intentFilter.addAction(AppConfigs.Action.ACTION_PROCESS_UPDATED)//更新流程状态
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(mRecevier, intentFilter, Context.RECEIVER_EXPORTED)
        } else {
            registerReceiver(mRecevier, intentFilter)
        }
    }

    class ProcessUpdatedRecevier(act: CreditApplyAct) : BroadcastReceiver() {
        var act = act
        override fun onReceive(context: Context, intent: Intent) {
            act.onRecevierEvent(intent)
        }
    }

    /**
     * 处理广播接收事件处理
     */
    private fun onRecevierEvent(intent: Intent){
        //根据需求添加自己需要关闭页面的action
        when(intent.action){
            AppConfigs.Action.ACTION_PROCESS_UPDATED -> {//更新流程状态
                HHLog.e("收到总流程刷新完成通知>>>>>>>>>>"+AppConfigs.getSPString(AppConfigs.SP_KEY.SP_HENECREDIT_PROCESS))
                if (isApplyClick){
                    presenter.loadProcessData()
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_APPLY_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_APPLY_END,"")
        if (mRecevier != null){
            unregisterReceiver(mRecevier)
        }
    }
}